/**
 * User: Paulo Fournier
 * Date: 13-08-2013
 * Map app controller
 */

Ext.define('Mobile-app.controller.Map', {
    extend: 'Ext.app.Controller',

    config: {
        //add view references for this controller
        refs: {
            mapPanel: 'mappanel',
            mobilePanel: 'mobilepanel'
        },

        //Definition of all listen events of this controller
        //can be triggered by the [fireEvent] method
        control: {

            mapPanel: {
                updateMobileMarkers: 'onUpdateMobileMarkers',
                addOnloadListener: 'onAddOnloadListener'
            }

        }

    },

    markers: null, //will contain the list of markers

    /***
     * Will load all marker
     */
    loadMobileMarkers: function () {

        //get store and map
        var store = this.getMobilePanel().down('list').getStore(),
            map = this.getMapPanel().down('map').getMap();

        this.markers = {};
        var list = [];

        this.bounds = new google.maps.LatLngBounds();

        var markerImage = new google.maps.MarkerImage(
            'resources/icons/level/none.png',
            new google.maps.Size(16, 16)
        );

        for (var i = 0; i < store.getCount(); i++) {
            var record = store.getAt(i);

            var lat = record.get('latitude'),
                lng = record.get('longitude');

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(lat, lng),
                title: record.get('reference'),
                icon: markerImage,
                id: record.get('id')
            });

            list.push(marker); //MarkerClusterer requires an array
            this.markers[record.get('id')] = marker; //save marker reference

            //show vehicle information after map tap
            (function (record) {
                google.maps.event.addDomListener(marker, 'click', function () {

                    //show marker alias and local onclick
                    Ext.Msg.alert(
                        record.data.reference,
                        record.data.local,
                        Ext.emptyFn
                    );
                });
            })(record);

            if (lat && lng)
                this.bounds.extend(new google.maps.LatLng(lat, lng));

        }

        //center markers
        map.fitBounds(this.bounds);

        //set cluster
        new MarkerClusterer(map, list, {gridSize: 40});

    },

    /***
     * Will update the markers postion on map
     */
    onUpdateMobileMarkers: function () {

        if (!this.markers) {
            this.loadMobileMarkers();
        }
        else {
            console.log('updateMobileMarkers position');
        }
    },

    /***
     * Will add a listener to the store to update markers after a reload
     */
    onAddOnloadListener: function () {

        //get store and mappanel
        var store = this.getMobilePanel().down('list').getStore(),
            mappanel = this.getMapPanel();

        //set listener to reload all markers after a store reload
        store.on('load',
            function (store, records, successful, operation, eOpts) {

                if (successful) {
                    this.fireEvent('updateMobileMarkers');
                }
            },
            mappanel
        );

        Ext.defer(this.setGoogleTrackerMarkerListener,500,this);

    },

    /***
     * Will add a listener to the google traker marker
     * so the user can add a POI based on this position
     */
    setGoogleTrackerMarkerListener: function(){

        //add listener to google tracker marker
        var marker = this.getMapPanel().down('map').getPlugins()[0].getMarker();

        (function (scope) {
            google.maps.event.addDomListener(marker, 'click', function () {

                Ext.Msg.confirm($.t('main.add poi'), $.t('main.add poi through device position'), function (buttonId) {
                    if (buttonId === 'yes') {

                        //set record with lat/lng
                        var record = Ext.create('Mobile-app.model.Mobile', {
                            latitude: this.getPosition().lat(),
                            longitude: this.getPosition().lng()
                        });

                        //show add poi panel
                        scope.getMapPanel().fireEvent('showAddPoiPanel', record);
                    }
                }, this);

            });
        })(this);

    }

});